﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reactive.Linq;
using System.Text;

using SomeKit.Http;

namespace SomeKit.Rx.Http
{
    public static partial class HttpHelper
    {
        public static IObservable<string> Post(this Uri uri, string body, Action<HttpWebRequest> headerHandler = null)
        {
            var request = uri.GetRequest(SomeKit.Http.HttpHelper.Verbs.POST, headerHandler);
            return PrepareBody(body, request);
        }

        public static IObservable<string> Post(this Uri uri, Action<HttpWebRequest> headerHandler = null)
        {
            return uri.Post(null, headerHandler);
        }

        public static IObservable<string> PostXml(this Uri uri, string body, Action<HttpWebRequest> headerHandler = null)
        {
            var request = uri.GetXmlRequest(SomeKit.Http.HttpHelper.Verbs.POST, true, headerHandler);
            return PrepareBody(body, request);
        }

        public static IObservable<string> PostJson(this Uri uri, string body, Action<HttpWebRequest> headerHandler = null)
        {
            var request = uri.GetJsonRequest(SomeKit.Http.HttpHelper.Verbs.POST, true, headerHandler);
            return PrepareBody(body, request);
        }

        private static IObservable<string> PrepareBody(string body, HttpWebRequest request)
        {
            if (string.IsNullOrEmpty(body))
            {
                return Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)().Select(r => r.WebResponseAsString());
            }
            else
            {
                byte[] buf = Encoding.UTF8.GetBytes(body); // assume post data is utf-8 encoded
                var f1 = Observable.FromAsyncPattern(request.BeginGetRequestStream, r1 => request.EndGetRequestStream(r1));
                return
                    from stream in f1()
                    let f2 = Observable.FromAsyncPattern(
                           (asynccallback, iasyncresult) => stream.BeginWrite(buf, 0, buf.Length, asynccallback, iasyncresult),
                            r2 => stream.EndWrite(r2))
                    from _ in f2()
                    let f3 = Observable.FromAsyncPattern(request.BeginGetResponse, r2 => request.EndGetResponse(r2))
                    from response in f3()
                    select response.WebResponseAsString();
            }
        }

    }
}
